package com.mofish.zbserver.user.login;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.mofish.zbserver.common.CommonService;
import com.mofish.zbserver.common.Result;
import com.mofish.zbserver.common.TokenUtils;
import com.mofish.zbserver.common.Utils;
import com.mofish.zbserver.common.model.user.User;

@RestController
@RequestMapping("/user/login")
public class LoginAPI {
	@Resource
	private CommonService commonService;
	
	@Resource
	private LoginService loginService;

	/**
	 * 登录
	 * @param loginDto 包含用户昵称与密码
	 * @return 登录成功返回success, 失败返回fail
	 */
	@PostMapping("")
	public Result login(@RequestBody LoginDto loginDto) {

		// 根据用户的昵称获取并设置用户uid
		String u_id = loginService.getU_idByU_name(loginDto.getU_name());
		loginDto.setU_id(u_id);

		// 查询帐号密码否允许正确
		loginDto.setU_pwd(Utils.pwdtool(loginDto.getU_pwd()));
		if (loginService.checkLogin(loginDto)) {
			// 登录成功
			String token = TokenUtils.loginSign(u_id, loginDto.getU_pwd());
			return Result.success("登录成功！", token);
		} else {
			// 登录失败
			return Result.fail(Result.ERR_CODE_BUSINESS ,"账号或密码错误！");
		}
	}

	/**
	 * 查询用户信息
	 * @param token 登录令牌
	 * @return 用户头像、昵称、id
	 */
	@GetMapping("/get/userInfo")
	public Result getUserInfoByToken(@RequestHeader("Token") String token) {
		String u_id = TokenUtils.getUserInfo(token, commonService).getU_id();
		User user = commonService.getUserWithoutU_pwdByU_id(u_id);
		return Result.successData(user);
	}

	/**
	 * 登出
	 * @param token 用户令牌
	 */
	@DeleteMapping("/exit")
	public Result exit(@RequestHeader("Token") String token) {
		try {
			TokenUtils.removeToken(token);

			return Result.successMsg("成功退出登录！");
		} catch (Exception e) {
			e.printStackTrace();
			return Result.fail(Result.ERR_CODE_SYS, "系统错误！退出失败！");
		}
	}
}
